using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class EnergyPanel : MonoBehaviour
{
    public Text energyText;
    public Text timeText;
    Coroutine timeCoroutine;
    static EnergyPanel instance;

    private void Awake()
    {
        if(instance==null) instance = this;
        else Destroy(gameObject);

        DontDestroyOnLoad(gameObject);    
    }

    private void Start()
    {
        if(GameManager.instance == null || !GameManager.instance.UseEnergy)
        {
            gameObject.SetActive(false);
        }
    }

    private void Update()
    {
        energyText.text = GameManager.Energy + "/" + GameManager.maxEnergy;

        if(GameManager.Energy < GameManager.maxEnergy)
        {
            if (!timeText.gameObject.activeSelf)
                timeText.gameObject.SetActive(true);
        }
        else
        {
            if (timeText.gameObject.activeSelf)
                timeText.gameObject.SetActive(false);

            if (timeCoroutine != null)
            {
                StopCoroutine(timeCoroutine);
                timeCoroutine = null;
            }
        }

        if (timeCoroutine == null && GameManager.Energy< GameManager.maxEnergy)
        {
            timeCoroutine = StartCoroutine(StartTime());
        }
    }

    IEnumerator StartTime()
    {
        TimeSpan timeSpan = new TimeSpan(0, 10, 0);
        DateTime targetTime = DateTime.Now.Add(timeSpan);

        while (true)
        {
            TimeSpan tempTime = targetTime - DateTime.Now;

            string[] strs = tempTime.ToString().Split(':');
            int minu = (int)(float.Parse(strs[2]));
            timeText.text = strs[1] + ":" + String.Format("{0:00}", minu);

            if (DateTime.Compare(targetTime, DateTime.Now)<0)
            {
                break;
            }
            yield return null;
        }
        timeCoroutine = null;
        GameManager.Energy++;
    }

    public void OnClickAdd()
    {
        FindObjectOfType<UImanager>().OnClickAddEnergy();
    }
}
